package beans;

import java.io.StreamCorruptedException;
import java.util.LinkedList;

import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;

import ourImage.OurPlanarImage;
import Listeners.ImageListener;
import events.ImageEvent;

/**
 * Source for reading the Image
 * 
 * @author Benjamin
 *
 */
public class SourceBean extends BaseBean implements Runnable {

	private String filePath;
	private BaseBean out;
	private LinkedList<ImageListener> listeners = new LinkedList<>();

	/**
	 * Constructor
	 * 
	 * @param filePath
	 *            for the Image
	 * @param out
	 */
	public SourceBean(String filePath, BaseBean out) {
		this.filePath = filePath;
		this.out = out;

	}

	public String getImagePath() {
		return filePath;
	}

	public void setImagePath(String path) {
		this.filePath = path;
	}

	@Override
	public OurPlanarImage read() throws StreamCorruptedException {
		// Read the next image from list
        if (!filePath.isEmpty()) {
            String fileName = filePath;
            try {
                PlanarImage image = JAI.create("fileload", fileName);
                // Build up the entity
                OurPlanarImage entity = new OurPlanarImage();
                entity.setImage(image);
                entity.setImageName(fileName);
                return entity;
            } catch (RuntimeException e) {
                System.out.println(e.getMessage());
            }
        }
		return null;
	}

	@Override
	public void write(OurPlanarImage value) throws StreamCorruptedException {
		// Do nothing

	}

	@Override
	public String getFilterName() {
		return "Source";
	}

	@Override
	public boolean isFilterEnabled() {
		return true;
	}

	@Override
	public void run() {
		System.out.println("Pipe gestartet in Push-Mode!");

		try {
			OurPlanarImage img = null;
			while ((img = read()) != null) {
				out.write(img);
			}
			out.write(null);
		} catch (StreamCorruptedException ex) {
			System.out.println(ex.getMessage());
		}

	}

	/*
	 * Bean Box Listeners
	 */
	public void addImageListener(ImageListener list) {
		listeners.add(list);

	}

	public void removeImageListener(ImageListener list) {
		listeners.add(list);
	}

	protected void notifyImageListener() {
		LinkedList<ImageListener> listens;
		ImageEvent event = new ImageEvent(this);
		synchronized (this) {
			listens = (LinkedList<ImageListener>) listeners.clone();
		}
		for (ImageListener l : listens) {
			l.onImageProceed(event);
		}
	}

}
